<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="标题" prop="Q_title_S_LK">
            <el-input v-model="queryData.Q_title_S_LK" placeholder="标题" />
          </el-form-item>
          <el-form-item label="类型" prop="Q_type_S_IN">
            <el-select v-model="queryData.Q_type_S_IN" placeholder="类型">
              <el-option label="公告" value="2" />
              <el-option label="消息" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="Q_status_S_EQ">
            <el-select v-model="queryData.Q_status_S_EQ" placeholder="状态">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfStatus"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送时间">
            <el-col :span="12">
              <el-date-picker v-model="queryData.Q_startTime_D_GE" class="width-130" type="date" value-format="yyyy-MM-dd" />
            </el-col>
            <el-col :span="2" class="line">-</el-col>
            <el-col :span="10">
              <el-date-picker v-model="queryData.Q_startTime_D_LE" class="width-130" type="date" value-format="yyyy-MM-dd" />
            </el-col>
          </el-form-item>

          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['log:message:delete']" v-if="tableData.length > 0" size="mini" plain type="warning" icon="el-icon-delete" @click="handleDeleteAll()">
              清空
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['log:message:delete']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" :columns="columns" />
        </el-row>
        <el-table
          ref="queryTable"
          v-loading="tableLoading"
          row-key="logId"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column v-if="columns[0].visible" align="center" label="标题" prop="title" show-overflow-tooltip />
          <el-table-column v-if="columns[1].visible" align="center" label="类型" prop="type" sortable width="100">
            <template slot-scope="scope">
              <el-tag :type="getDictType('type', scope.row.type)" v-text="getDictValue('type', scope.row.type)" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[2].visible" align="center" label="消息中间件" prop="messageType" sortable width="110">
            <template slot-scope="scope">
              <el-tag type="primary" v-text="scope.row.messageType" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[3].visible" align="center" label="内容" prop="content" show-overflow-tooltip />
          <el-table-column v-if="columns[4].visible" align="center" label="接收人" prop="address" width="100" show-overflow-tooltip />
          <el-table-column v-if="columns[5].visible" align="center" label="主题" prop="topic" show-overflow-tooltip />
          <el-table-column v-if="columns[6].visible" align="center" label="路由" prop="router" show-overflow-tooltip />
          <el-table-column v-if="columns[7].visible" align="center" label="重试次数" prop="retryCount" width="90" show-overflow-tooltip />
          <el-table-column v-if="columns[8].visible" align="center" label="发送状态" sortable width="105" prop="status">
            <template slot-scope="scope">
              <el-tag :type="getDictType('status', scope.row.status)" v-text="getDictValue('status', scope.row.status)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="错误消息" prop="desc" width="140" show-overflow-tooltip>
            <template slot-scope="scope">
              <span style="cursor: pointer" @click="handleError(scope.row)">{{ scope.row.desc | ellipsis }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columns[9].visible" align="center" label="发送时间" prop="startTime" width="180" show-overflow-tooltip />
          <el-table-column v-if="columns[10].visible" align="center" label="执行时间" prop="execTime" width="150" show-overflow-tooltip />
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>
    <el-dialog v-el-drag-dialog title="错误信息" :visible.sync="showError" :append-to-body="true">
      <el-card>
        <el-row class="m-b-20">
          <el-col :span="5">
            <span style="font-weight: bold">消息中间件</span>
          </el-col>
          <el-col :span="19">
            <el-tag type="success" v-text="detail.messageType" />
          </el-col>
        </el-row>
        <el-row class="m-b-20">
          <el-col :span="5">
            <span style="font-weight: bold">主题/路由</span>
          </el-col>
          <el-col :span="19">
            <el-tag type="success" v-text="detail.function" />
          </el-col>
        </el-row>
        <el-row>
          <json-viewer :value="detail.json" expanded :expand-depth=3 boxed sort></json-viewer>
        </el-row>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { messageLogTable, messageLogDelete } from '@/api/system/log'
import JsonViewer from 'vue-json-viewer'
import 'vue-json-viewer/style.css'

export default {
  components: {
    JsonViewer
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_title_S_LK: undefined,
        Q_type_S_IN: undefined,
        Q_status_S_EQ: undefined,
        Q_startTime_D_GE: undefined,
        Q_startTime_D_LE: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      columns: [
        { key: 0, label: `标题`, visible: true },
        { key: 1, label: `类型`, visible: true },
        { key: 2, label: `消息中间件`, visible: true },
        { key: 3, label: `内容`, visible: true },
        { key: 4, label: `接收人`, visible: true },
        { key: 5, label: `主题`, visible: true },
        { key: 6, label: `路由`, visible: true },
        { key: 7, label: `重试次数`, visible: true },
        { key: 8, label: `发送状态`, visible: true },
        { key: 9, label: `发送时间`, visible: true },
        { key: 10, label: `执行时间`, visible: true }
      ],
      selectionData: [],
      optionOfType: [{
        dictValue: '2',
        dictLabel: '公告',
        cssClass: 'success'
      }, {
        dictValue: '3',
        dictLabel: '消息',
        cssClass: 'primary'
      }],
      optionOfStatus: [],
      showError: false,
      detail: {}
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.getDictData()
      this.getTableData()
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getDictData() {
      this.$dictGroup('sys_message_send_status').then(response => {
        this.optionOfStatus = response
      }).catch(e => {})
    },
    getDictType(property, value) {
      return this.getDictElement(property, value)[2]
    },
    getDictValue(property, value) {
      return this.getDictElement(property, value)[1]
    },
    getDictElement(property, value) {
      if (property === 'status') {
        return this.$api.getDictElement(this.optionOfStatus, value)
      } else if (property === 'type') {
        return this.$api.getDictElement(this.optionOfType, value)
      }
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      messageLogTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.queryTable.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleError(row) {
      this.detail = {
        messageType: '',
        function: '',
        json: ''
      }

      if (row.desc) {
        let json = row.desc.replaceAll('\\"', '')
        this.detail = {
          messageType: row.messageType,
          function: row.topic ? row.topic : row.router,
          json: JSON.parse(json)
        }
      }

      this.showError = true
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function(row, index) {
        return row.logId
      }).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        messageLogDelete({ ids: id }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    },
    handleDeleteAll() {
      this.$confirm('是否清空数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        messageLogDelete({}).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    }
  }
}
</script>
